import axios, { AxiosRequestConfig, Method } from '@ohos/axios'
import {BaseData} from './model/BaseData'
import { LogUtils } from '@library/utils'

const BASE_URL = 'http://buynewcar.api.autohome.com.cn'

const headers = {
  'Content-type': 'application/json;charset=UTF-8'
}
const service = axios.create({
  timeout: 60 * 1000,
  baseURL: BASE_URL,
  headers
})

//请求拦截器
service.interceptors.request.use(config => {
  LogUtils.i(`--发送请求接口：${config.baseURL + config.url}`)
  LogUtils.i(`--发送请求方式：${config.method}`)
  LogUtils.i(`--发送请求参数：${config.method == "get" || config.method == "GET" ? config.params : config.data}`)
  return config
}, err => {
  return err
})

service.interceptors.response.use(response => {
  let config = response.config
  LogUtils.i(`--接收请求接口：${config.baseURL + config.url}`)
  LogUtils.i(`--接收请求方式：${config.method}`)
  LogUtils.i(`--接收请求参数：${config.method == "get" || config.method == "GET" ? config.params : config.data}`)
  let jsonString = JSON.stringify(response.data)
  if (jsonString.length < 1023) {
    LogUtils.i(`--接收请求响应：${jsonString}`)
  } else {
    LogUtils.i(`--接收请求响应内容过长`)
    LogUtils.i(jsonString)
  }

  return response
}, error => {
  return Promise.reject(error)
})
//响应拦截器
service.interceptors.response.use(response => {
  if (response.status == 200) {
    let data = response.data
    if (data.returncode == 0) {
      return response.data
    } else {
      return Promise.reject(data.message)
    }
  }
  return Promise.reject(response.statusText || `服务异常${response.status}`)
}, error => {
  return Promise.reject(error)
})


export function axiosPost<T>(url: string, data?: any, axiosConfig?: Omit<AxiosRequestConfig, "url" | "method" | "data">): Promise<BaseData<T>> {
  return service.post<T, BaseData<T>>(url, data, axiosConfig)
}

export function axiosGet<T>(url: string, params?: any, axiosConfig?: Omit<AxiosRequestConfig, "url" | "method" | "params">): Promise<BaseData<T>> {
  let config: AxiosRequestConfig = {
    params,
    ...axiosConfig
  }
  return service.get<T, BaseData<T>>(url, config)
}
